package com.dtu.distributed.thread;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import com.dtu.distributed.controller.TempController;
import com.dtu.distributed.enums.Action;
import com.dtu.distributed.generator.TemperatureGenerator;

public class TemperatureThread extends Thread {
	
	private static final long TEMPERATURE_INTERVAL = 10*1000;
	private static final int TEMPERATURE = 25;
	
	private DatagramSocket socket;
	private TemperatureGenerator tempGenerator;
	private boolean runThread = true;

	public TemperatureThread() {
		this.tempGenerator = new TemperatureGenerator(TEMPERATURE);
		setupSocket();
	}

	public void setupSocket() {
		try {
			this.socket = new DatagramSocket();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		
		while (runThread) {
			System.out.println("check" + TempController.adminTemperatureIpAddress + ": " + TempController.adminTemperaturePort );
			
			if (TempController.adminTemperatureIpAddress != null && TempController.adminTemperaturePort != -1) {
				String message = Action.TEMPERATURE + ":" + Integer.toString(tempGenerator.getBinomial());
				byte[] msg = message.getBytes();
				
				System.out.println("Generated temp: " + message);
							
				try {
					InetAddress host = InetAddress.getByName(TempController.adminTemperatureIpAddress);
					DatagramPacket messageOut = new DatagramPacket(msg, msg.length, host, TempController.adminTemperaturePort);
					socket.send(messageOut);
					System.out.println("Success generated");
					Thread.sleep(TEMPERATURE_INTERVAL);
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					runThread = false;
					System.out.println("Temperature node stopped");
					//  e.printStackTrace();
				}
			}
		}
		socket.close();
	}

}
